package com.tanchengjin.admin.modules.blog.controller;

import com.tanchengjin.admin.exception.ApplicationException;
import com.tanchengjin.admin.modules.blog.service.UserService;
import com.tanchengjin.admin.modules.blog.validations.UsernamePasswordValidate;
import com.tanchengjin.admin.utils.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Controller
public class AuthenticationController {
    private final static Logger logger = LoggerFactory.getLogger(AuthenticationController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/auth/login.html")
    public String loginPage() {
        if (isLogin()) return "redirect:/";
        return "/index/auth/login";
    }

    @GetMapping("/auth/register.html")
    public String registerPage() {
        if (isLogin()) return "redirect:/";
        return "/index/auth/register";
    }

    @PostMapping("/auth/register")
    @ResponseBody
    public ServerResponse register(HttpServletRequest request, @Valid UsernamePasswordValidate usernamePasswordValidate) throws ServletException {
        try {
            userService.createUserByUsername(usernamePasswordValidate.getUsername(), usernamePasswordValidate.getPassword());
        } catch (ApplicationException exception) {
            return ServerResponse.responseWithFailureMessage(exception.getMessage());
        }
        //注册成功写入session
        request.login(usernamePasswordValidate.getUsername(), usernamePasswordValidate.getPassword());

        return ServerResponse.responseWithSuccess("注册成功");
    }

    private boolean isLogin() {
        SecurityContext context = SecurityContextHolder.getContext();

        if (context != null && context.getAuthentication().isAuthenticated() && !(context.getAuthentication() instanceof AnonymousAuthenticationToken)) {
            return true;
        }
        return false;
    }
}
